using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using bookmeetingroom.Data.Entities;
using Microsoft.AspNetCore.Identity;

namespace bookmeetingroom.Data
{
    public static class DbContextExtensions
    {
        public static UserManager<ApplicationUser> UserManager { get; set; }
        public static RoleManager<ApplicationRole> RoleManager { get; set; }
        public static async Task EnsureSeeded(this ApplicationDbContext context)
        {
            //add a default company
            if (!context.Companies.Any(n => n.Name == "默认"))
            {
                var defaultCompany = new Company
                {
                    Name = "默认",
                    UpdatedBy="system",
                    CreatedBy="system",
                    UpdatedTime=DateTime.Now,
                    CreatedTime=DateTime.Now
                };

                context.Companies.Add(defaultCompany);

                context.SaveChanges();
            }
            //create admin role
            if (await RoleManager.RoleExistsAsync("Admin") == false)
            {
                await RoleManager.CreateAsync(new ApplicationRole("Admin"));
            }
            //create employee role
            if (await RoleManager.RoleExistsAsync("Employee") == false)
            {
                await RoleManager.CreateAsync(new ApplicationRole("Employee"));
            }
            //create an admin account
            if (await UserManager.FindByEmailAsync("mi.tian2008@aliyun.com") == null)
            {
                var defaultCompany = context.Companies.FirstOrDefault(n => n.Name == "默认");

                if (defaultCompany != null)
                {
                    var admin = new ApplicationUser
                    {
                        UserName = "13700000000",
                        Email = "mi.tian2008@aliyun.com",
                        EmailConfirmed = true,
                        LockoutEnabled = false,
                        CompanyId = defaultCompany.Id
                    };

                    await UserManager.CreateAsync(admin, "Admin@123456");

                    if (await UserManager.IsInRoleAsync(admin, "Admin") == false)
                    {
                        await UserManager.AddToRoleAsync(admin, "Admin");
                    }
                }
            }

            //var admin = await UserManager.FindByEmailAsync("mi.tian2008@aliyun.com");

            //if (admin != null)
            //{
            //    if (await UserManager.IsInRoleAsync(admin, "Admin") == false)
            //    {
            //        await UserManager.AddToRoleAsync(admin, "Admin");
            //    }
            //}


        }
        


    }
}